<?php
require('config.php');

		$user_id=$_REQUEST['user_id'];
        $goods_id=$_REQUEST['goods_id'];
        $pay_way=4;
		$address=$_REQUEST['address'];
		$num=$_REQUEST['num'];

		$sql="select * from `".$oto."_users` where `userId`='".$user_id."' LIMIT 1";
		$result=$db->query($sql);
		while($row=$result->fetch_assoc()){
			$user_info[]=$row;//将取得的所有数据赋值给person_info数组
		}
		$sql="select * from `".$oto."_integral` where `goodsId`='".$goods_id."' LIMIT 1";
		$result=$db->query($sql);
		while($row=$result->fetch_assoc()){
			$goods_info[]=$row;//将取得的所有数据赋值给person_info数组
		}
		$sql="select * from `".$oto."_user_address` where `addressId`='".$address."' LIMIT 1";
		$result=$db->query($sql);
		while($row=$result->fetch_assoc()){
			$address_info[]=$row;//将取得的所有数据赋值给person_info数组
		}
		if(!isset($user_info))
		{
			$data[0]['pan']='-1';
			$data[0]['msg']='用户不存在';
			echo json_encode($data);
			exit();
		}
		if(!isset($address_info))
		{
			$data[0]['pan']='-1';
			$data[0]['msg']='地址不存在，请重新选择收货地址';
			echo json_encode($data);
			exit();
		}
		if(!isset($goods_info))
		{
			$data[0]['pan']='-1';
			$data[0]['msg']='商品不存在';
			echo json_encode($data);
			exit();
		}
		else
		{
			if($goods_info[0]['isSale']==0)
			{
				$data[0]['pan']='-1';
				$data[0]['msg']='该商品已下架';
				echo json_encode($data);
				exit();
			}
			if($goods_info[0]['goodsFlag']==0)
			{
				$data[0]['pan']='-1';
				$data[0]['msg']='商品不存在';
				echo json_encode($data);
				exit();
			}
			if($goods_info[0]['goodsStock']<=0 || $goods_info[0]['goodsStock']<$num)
			{
				$data[0]['pan']='-1';
				$data[0]['msg']='商品库存不足';
				echo json_encode($data);
				exit();
			}
		}
		if($pay_way==4 && $user_info[0]['userScore']<$goods_info[0]['shopPrice']*$num)
		{
				$data[0]['pan']='-1';
				$data[0]['msg']='可用积分不足';
				echo json_encode($data);
				exit();
		}

		//验证通过，开始减库存，加销量，减积分，增加积分消费记录，增加订单，增加商户提醒
		$hgoodsStock=$goods_info[0]['goodsStock']-1;
		$hsaleCount=$goods_info[0]['saleCount']+1;
		if($hgoodsStock==0)//开始减库存，加销量
		{
			$sql="update ".$oto."_integral set goodsStock='{$hgoodsStock}',saleCount='{$hsaleCount}',isSale='0' where goodsId='{$goods_id}'";
			$result=$db->query($sql);
		}
		else if($hgoodsStock>0)
		{
			$sql="update ".$oto."_integral set goodsStock='{$hgoodsStock}',saleCount='{$hsaleCount}' where goodsId='{$goods_id}'";
			$result=$db->query($sql);
		}

		if($pay_way==4)//减积分
		{
			$huserScore=$user_info[0]['userScore']-$goods_info[0]['shopPrice']*$num;
			$sql="update ".$oto."_users set userScore='{$huserScore}' where userId='{$user_id}'";
			$result=$db->query($sql);
		}
		
		//增加订单
		$orderNo=microtime(true)*10000;//订单号
		$areaId1=$address_info[0]['areaId1'];
		$areaId2=$address_info[0]['areaId2'];
		$areaId3=$address_info[0]['areaId3'];
		$lng=$address_info[0]['lng'];
		$lat=$address_info[0]['lat'];
		$orderStatus=0;
		if($pay_way==4) $totalMoney=$goods_info[0]['shopPrice']*$num;
		if($pay_way==1) $totalMoney=$goods_info[0]['marketPrice']*$num;
		if($pay_way==2) $totalMoney=$goods_info[0]['marketPrice']*$num;
		if($pay_way==3) $totalMoney=$goods_info[0]['marketPrice']*$num;
		$deliverType=0;//配送方式
		$userName=$address_info[0]['userName'];
		$communityId=$address_info[0]['communityId'];
			$dizhi='';
			$sql="select * from `".$oto."_areas` where `areaId`='".$address_info[0]['areaId1']."'";
			$result=$db->query($sql);
			while($row=$result->fetch_assoc()){
				$sheng[0]=$row;//将取得的所有数据赋值给person_info数组
			}
			$sql="select * from `".$oto."_areas` where `areaId`='".$address_info[0]['areaId2']."'";
			$result=$db->query($sql);
			while($row=$result->fetch_assoc()){
				$shi[0]=$row;//将取得的所有数据赋值给person_info数组
			}
			$sql="select * from `".$oto."_areas` where `areaId`='".$address_info[0]['areaId3']."'";
			$result=$db->query($sql);
			while($row=$result->fetch_assoc()){
				$xian[0]=$row;//将取得的所有数据赋值给person_info数组
			}
			// $sql="select * from `".$oto."_communitys` where `communityId`='".$address_info[0]['communityId']."'";
			// $result=$db->query($sql);
			// while($row=$result->fetch_assoc()){
			// 	$jiedao[0]=$row;//将取得的所有数据赋值给person_info数组
			// }
			$dizhi=$sheng[0]['areaName'].$shi[0]['areaName'].$xian[0]['areaName'].$address_info[0]['address'];
		$userAddress=$dizhi;
		$userPhone=$address_info[0]['userPhone'];
		$orderScore=$totalMoney;
		$requireTime=0;//期望送达时间
		$createTime=date('Y-m-d H:i:s');//下单时间
		$time=time();
		$orderunique=floor(microtime(true)*1000);//是否同一批下单
		$needPay=$totalMoney;//应付金额
		$sql="INSERT INTO ".$oto."_orders (`orderNo`,`areaId1`,`areaId2`,`areaId3`,`orderStatus`,`totalMoney`,`deliverType`,`userId`,`userName`,`communityId`,`userAddress`,`userPhone`,`orderScore`,`orderRemarks`,`createTime`,`orderunique`,`needPay`,`orderType`,`payType`,`isPay`) VALUES ('$orderNo','$areaId1','$areaId2','$areaId3','$orderStatus','$totalMoney','$deliverType','$user_id','$userName','$communityId','$userAddress','$userPhone','$orderScore','','$createTime','$orderunique','$needPay','4','$pay_way','1')";
        $result2=$db->query($sql);//插入order表
        file_put_contents("tsxx.txt", "\r\n".$sql."\r\n", FILE_APPEND);
        $sql="select * from `".$oto."_orders` where `orderNo`='".$orderNo."' and `userId`='{$user_id}' and `orderunique`='{$orderunique}'";
		$result=$db->query($sql);//查询刚插进去的orderId
		while($row=$result->fetch_assoc()){
			$order[0]=$row;//将取得的所有数据赋值给person_info数组
		}
		$orderId=$order[0]['orderId'];
		$goodsPrice=$goods_info[0]['shopPrice'];
		$goodsName=$goods_info[0]['goodsName'];
		$goodsThums=$goods_info[0]['goodsImg'];
        $sql="INSERT INTO ".$oto."_order_goods (`orderId`,`goodsId`,`goodsNums`,`goodsPrice`,`goodsName`,`goodsThums`,`goodsGroupId`) VALUES ('$orderId','$goods_id','$num','$goodsPrice','$goodsName','$goodsThums','0')";
        $result=$db->query($sql);//插入order对应的order_goods表
		//增加订单end
        //file_put_contents("tsxx.txt", "\r\n".$sql."\r\n", FILE_APPEND);
		//增加积分消费记录
		if($pay_way==4)
		{
	        $sql="INSERT INTO ".$oto."_score_record (`userid`,`orderNo`,`score`,`totalscore`,`time`,`IncDec`,`type`) VALUES ('$user_id','$orderNo','$totalMoney','$huserScore','$time','0','7')";
	        $result=$db->query($sql);
		}
		//file_put_contents("tsxx.txt", "\r\n".$sql."\r\n", FILE_APPEND);
		if($result2)
		{
			$data[0]['pan']='1';
			$data[0]['msg']='兑换成功';
		}
		else
		{
			$data[0]['pan']='-1';
			$data[0]['msg']='兑换异常';
		}
		echo json_encode($data);
?>